package com.suntop.carousel.qlmediaplay.picture;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.suntop.carousel.qlmediaplay.field.Field_Scale;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayEventListener;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayer;
import com.suntop.carousel.qlmediaplay.tools.PictureCacheTool;
import com.suntop.carousel.qlmediaplay.video.player.ICoverView;
import com.suntop.carousel.qlmediaplay.video.player.IMediaPlayerControl;
import com.suntop.carousel.qlmediaplay.video.player.IVideoPlayer;

import java.io.File;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;


public class QLPictureView extends AppCompatImageView implements IMediaPlayer
        , RequestListener<Drawable> {
    private String url = "";
    private int qlTag = 0;
    private int type = 0;
    private int scale = Field_Scale.Scale_Default;
    private IMediaPlayEventListener listener;
    private long time = 5000;
    private boolean autoCache = false;
    private boolean isPlaying = false;//正则播放
    private RequestOptions requestOptions;
    private String error = "";
    private String realUrl = "";
    private DecodeFormat decodeFormat;

    public QLPictureView(@NonNull Context context) {
        super(context);

    }


    public QLPictureView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }

    public QLPictureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }


    @Override
    public IMediaPlayer init(IVideoPlayer iVideoPlayer) {
        return this;
    }

    @Override
    public IMediaPlayer initFarm(DecodeFormat decodeFormat) {
        this.decodeFormat=decodeFormat;
        return this;
    }


    @Override
    public IMediaPlayer addEventListener(IMediaPlayEventListener listener) {
        this.listener = listener;
        return this;
    }

    @Override
    public IMediaPlayEventListener getEventListener() {
        return listener;
    }

    @Override
    public IMediaPlayer setDate(String playUrl) {
        this.url = playUrl;
        return this;
    }

    @Override
    public IMediaPlayer setDate(AssetFileDescriptor fileDescriptor) {
        return this;
    }

    @Override
    public String getPlayUrl() {
        return this.url;
    }

    @Override
    public IMediaPlayer setScaleType(int scaleType) {
        this.scale = scaleType;
        return this;
    }

    @Override
    public int getScale() {
        return this.scale;
    }

    @Override
    public IMediaPlayer setDelayTime(long time) {
        this.time = time;
        return this;
    }

    @Override
    public long getDelayTime() {
        return this.time;
    }

    @Override
    public IMediaPlayer autoCache(boolean auto) {
        this.autoCache = auto;
        return this;
    }

    @Override
    public IMediaPlayer addIConView(ICoverView iCoverView, boolean isNeedBitmap) {

        return this;
    }

    @Override
    public IMediaPlayer addController(IMediaPlayerControl control) {
        return this;
    }

    @Override
    public IMediaPlayer setReBack(boolean isReBack) {
        return this;
    }

    @Override
    public boolean isPlaying() {
        return isPlaying;
    }

    /**
     * 设置数据的时候要调用这个
     */
    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    @SuppressLint({"CheckResult", "NewApi"})
    @Override
    public void build(boolean isPlaying) {
        if (null == requestOptions) {
            requestOptions = new RequestOptions()
                    .error(this.getDrawable())
                    .placeholder(this.getDrawable())
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .dontTransform();
        }
        if (decodeFormat!=null){
            requestOptions.format(decodeFormat);
            Log.e("图片压缩","screenWith=="+screenWith+" ="+screenHeight);
            requestOptions.override(screenWith,screenHeight);
        }

        switch (scale) {
            case Field_Scale.Scale_Match:
                this.setScaleType(ImageView.ScaleType.FIT_XY);
                break;
            case Field_Scale.Scale_Crop:
                this.setScaleType(ImageView.ScaleType.CENTER_CROP);
                break;
            default:
                this.setScaleType(ImageView.ScaleType.FIT_CENTER);
                break;
        }
        realUrl = url;
        if (autoCache && (url.startsWith("http")
                || url.startsWith("www"))) {
            startCache();
        } else {
            if (isCanLoad()) {
                Glide.with(getContext())
                        .load(realUrl)
                        .apply(requestOptions)
                        .into(this);
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    private void startCache() {
        String absolutePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath();
        PictureCacheTool.getInstance().loadPictureFirst(getContext()
                , url, absolutePath, new PictureCacheTool.OnLoadPictureImageListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public void onLoadImage(File file) {
                        if (file != null) {
                            realUrl = file.getAbsolutePath();
                        }
                        if (isCanLoad()) {
                            Glide.with(getContext())
                                    .load(realUrl)
                                    .apply(requestOptions)
                                    .into(QLPictureView.this);
                        }
                    }
                });
    }

    @Override
    public void startPlay() {
        if (getContext() == null) {
            return;
        }
        isPlaying = true;
        if (getEventListener() != null) {
            getEventListener().startMediaPlay(0, 0, url);
        }
        removeCallbacks(task);
        this.postDelayed(task, time);
    }

    @Override
    public void pausePlay() {
        removeCallbacks(task);
    }

    @Override
    public void stopPlay() {
        isPlaying = false;
        removeCallbacks(task);
    }

    @Override
    public void pauseTo() {
        isPlaying = false;
        removeCallbacks(task);
    }

    @Override
    public void reSetCupPicture() {

    }
    private int screenWith;
    private int screenHeight;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        screenHeight=MeasureSpec.getSize(heightMeasureSpec);
        screenWith=MeasureSpec.getSize(widthMeasureSpec);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private boolean isCanLoad(){
        if (getContext()==null){
            return false;
        }
        if (getContext() instanceof Activity){
            boolean destroyed = ((Activity) getContext()).isDestroyed();
            return !destroyed;
        }
        return false;
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void releasePlay() {
        if (getContext() != null) {
            if (getContext() instanceof Activity){
                boolean destroyed = ((Activity) getContext()).isDestroyed();
                if (!destroyed){
                    Glide.with(getContext())
                            .clear(this);
                }
            }else if (getContext() instanceof ContextWrapper){
                Glide.with(getContext().getApplicationContext())
                        .clear(this);
            }
        }
        isPlaying = false;
        removeCallbacks(task);

    }

    @Override
    public void releaseNoClear() {

    }

    @Override
    public IMediaPlayer setMediaType(int type) {
        return this;
    }

    @Override
    public View getQLView() {
        return this;
    }

    @Override
    public IMediaPlayer setVoice(float left, float right) {
        return this;
    }

    @Override
    public IMediaPlayer setLoop(boolean isLoop) {
        return this;
    }

    @Override
    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
        isPlaying = false;
        error = "" + e;
        this.postDelayed(task, time);
        return false;
    }

    @Override
    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
        isPlaying = true;
        error = "";
        this.postDelayed(task, time);
        return false;
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (getEventListener() != null) {
                getEventListener().finishMediaPlay(0, 0
                        , url, error);
            }
        }
    };


}
